package com.lzy.product.apis.impl;

import com.github.pagehelper.PageInfo;
import com.lzy.approval.apis.EventServiceApi;
import com.lzy.approval.apis.OnProcessListener;
import com.lzy.approval.apis.TaskServiceApi;
import com.lzy.approval.dtos.EventDto;
import com.lzy.base.apis.SysResourceServiceApi;
import com.lzy.base.dtos.SysResourceDto;
import com.lzy.framework.common.dtos.LicenseDto;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.product.apis.*;
import com.lzy.product.constants.BusinessType;
import com.lzy.product.dtos.*;
import com.lzy.product.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by WIN7 on 2017/11/28.
 */
@Service
public class ProductInfoServiceApiImpl implements ProductInfoServiceApi {

    @Autowired
    ProductInfoService produceInfoService;
    @Autowired
    ProductImageTextServiceApi productImageTextServiceApi;
    @Autowired
    ProductInfoClassifyServiceApi productInfoClassifyServiceApi;
    @Autowired
    ProductClassifyServiceApi productClassifyServiceApi;
    @Autowired
    ProductInfoProjectServiceApi productInfoProjectServiceApi;
    @Autowired
    ProjectServiceApi projectServiceApi;
    @Autowired
    TaskServiceApi taskServiceApi;
    @Autowired
    EventServiceApi eventServiceApi;
    @Autowired
    SysResourceServiceApi sysResourceServiceApi;

    @Override
    public Long insert(ProductInfoDto dto) {
        return produceInfoService.insert(dto);
    }

    @Override
    public Boolean update(ProductInfoDto dto) {
        return produceInfoService.update(dto);
    }

    @Override
    public Boolean delete(Long id) {
        return produceInfoService.delete(id);
    }

    @Override
    public Boolean remove(Long id) {
        return produceInfoService.remove(id);
    }

    @Override
    public ProductInfoDto findById(Long id) {
        ProductInfoDto productInfoDto = produceInfoService.findById(id);
        if (productInfoDto != null) {
            //获取图文详情
            ProductImageTextDto pitDto = new ProductImageTextDto();
            pitDto.setProductId(id);
            List<ProductImageTextDto> pitDtoList = productImageTextServiceApi.query(pitDto);
            if (pitDtoList != null) {
                productInfoDto.setDetailImages(pitDtoList);
            }
            //获取分类信息
            ProductInfoClassifyDto picDto = new ProductInfoClassifyDto();
            picDto.setInfoId(id);
            ProductInfoClassifyDto productInfoClassifyDto = productInfoClassifyServiceApi.selectProductClassify(picDto);
            if (productInfoClassifyDto != null && productInfoClassifyDto.getClassifyId() != null) {
                ProductClassifyDto pcDto = productClassifyServiceApi.findById(productInfoClassifyDto.getClassifyId());
                if (pcDto != null) {
                    productInfoDto.setClassifyId(pcDto.getId());
                    productInfoDto.setClassifyName(pcDto.getName());
                }
            }
        }
        return productInfoDto;
    }

    @Override
    public List<ProductInfoDto> query(ProductInfoDto dto) {
        return produceInfoService.query(dto);
    }

    @Override
    public Long addProduct(ProductInfoDto dto, String[] param, LicenseDto lic) {
        Ensure.that(dto).isNotNull("01000003");
        Long id = produceInfoService.insert(dto);
        Ensure.that(param).isNotNull("01000003");
        Ensure.that(param.length).isEqual(5, "00000001");
        Ensure.that(lic).isNotNull("01000003");
        String name ;
        if(param[2]==null||param[2].equals("")){
            name = param[1];
        }else{
            name = param[2];
        }
        // 发起审核
        Long applicantId            = Long.parseLong(param[0]);//UserUtil.getCurrentUser().getId();                // 申请人id
        String applicantName        = name;//UserUtil.getCurrentUser().getLoginName();         // 申请人名称
        String applicantType        = param[4];//getLoginUserRoleNames();                          // 申请人身份
        String businessKey          = id.toString();                                    // 业务数据Id
        String businessName         = dto.getName();                                // 业务数据名称
        String businessUrl          = lic.getUrl() + id;              // 业务数据预览地址

        taskServiceApi.startProcessInstance(lic.getCode(), applicantId, applicantName, applicantType, businessKey, businessName, businessUrl, new OnProcessListener() {
            @Override
            public void onProcessDisabled(String businessKey) {
                // 流程禁用时，直接通过审核
                Long assigneeId = applicantId;//UserUtil.getCurrentUser().getId();
                String assigneeName = applicantName;//UserUtil.getCurrentUser().getLoginName();
                updateVerifyStatusById(Long.parseLong(businessKey), BusinessType.VerifyStatusEnum.YESVERIFY.getK(), assigneeId,assigneeName,"审核成功后自动上架",applicantId);
            }
        });
        return id;
    }

    @Override
    public Boolean updateProduct(ProductInfoDto infoDto, String[] param, LicenseDto lic) {
        ProductInfoDto dto = produceInfoService.findById(infoDto.getId());
        Boolean ok;
        if(dto != null && dto.getVerifyStatus() != BusinessType.VerifyStatusEnum.VERIFY.getK()) {
            SysResourceDto sysResourceDto = sysResourceServiceApi.findByCode(lic.getCode());
            //判断该资源表中是否有绑有审核事件
            if (sysResourceDto != null && sysResourceDto.getEventId() != null ) {
                EventDto eventDto = eventServiceApi.findById(sysResourceDto.getEventId());
                //判断绑定的事件是否启用
                if (eventDto != null && eventDto.getStatus() == BusinessType.StatusEnum.ENABLED.getCode()){
                    infoDto.setVerifyStatus(BusinessType.VerifyStatusEnum.VERIFY.getK());
                    ok = produceInfoService.update(infoDto);
                    Ensure.that(ok).isTrue("01000007");
                    Ensure.that(param).isNotNull("01000003");
                    Ensure.that(param.length).isEqual(5, "00000001");
                    Ensure.that(lic).isNotNull("01000003");
                    String name ;
                    if (param[2] == null || param[2].equals("")) {
                        name = param[1];
                    } else {
                        name = param[2];
                    }
                    Long id = infoDto.getId();
                    // 发起审核
                    Long applicantId = Long.parseLong(param[0]);//UserUtil.getCurrentUser().getId();                // 申请人id
                    String applicantName = name;//UserUtil.getCurrentUser().getLoginName();         // 申请人名称
                    String applicantType = param[4];//getLoginUserRoleNames();                          // 申请人身份
                    String businessKey = id.toString();                                    // 业务数据Id
                    String businessName = infoDto.getName();                                // 业务数据名称
                    String businessUrl = lic.getUrl() + id;              // 业务数据预览地址

                    taskServiceApi.startProcessInstance(lic.getCode(), applicantId, applicantName, applicantType, businessKey, businessName, businessUrl, new OnProcessListener() {
                        @Override
                        public void onProcessDisabled(String businessKey) {
                            // 流程禁用时，直接通过审核
                            Long assigneeId = applicantId;//UserUtil.getCurrentUser().getId();
                            String assigneeName = applicantName;//UserUtil.getCurrentUser().getLoginName();
                            updateVerifyStatusById(Long.parseLong(businessKey), BusinessType.VerifyStatusEnum.YESVERIFY.getK(), assigneeId, assigneeName, "审核成功后自动上架", applicantId);
                        }
                    });
                }else{
                    ok = produceInfoService.update(infoDto);
                    Ensure.that(ok).isTrue("01000007");
                }
            } else {
                ok = produceInfoService.update(infoDto);
                Ensure.that(ok).isTrue("01000007");
            }
        }else{
            ok = produceInfoService.update(infoDto);
            Ensure.that(ok).isTrue("01000007");
        }
        return ok;
    }

    @Override
    public PageInfo<ProductInfoDto> selectList(Pager pager, ProductInfoDto dto) {
        return produceInfoService.selectList(pager, dto);
    }

    @Override
    public Integer updateList(Integer shelves, String ids) {
        return produceInfoService.updateList(shelves, ids);
    }

    @Override
    public ProductInfoDto getProductProject(Long productId) {
        ProductInfoDto productInfoDto = produceInfoService.findById(productId);
        if (productInfoDto != null && productInfoDto.getId() != null) {
            //获取产品与包含项的关联关系
            ProductInfoProjectDto productInfoProjectDto = new ProductInfoProjectDto();
            productInfoProjectDto.setProductId(productId);
            List<ProductInfoProjectDto> productInfoProjectDtoList = productInfoProjectServiceApi.query(productInfoProjectDto);
            if (productInfoProjectDtoList != null && productInfoProjectDtoList.size() > 0) {
                for (ProductInfoProjectDto infoProjectDto : productInfoProjectDtoList) {
                    if (infoProjectDto != null && infoProjectDto.getProjectId() != null) {
                        ProjectDto projectDto = projectServiceApi.getById(infoProjectDto.getProjectId());
                        if (projectDto != null) {
                            infoProjectDto.setUnit(projectDto.getUnit());
                            infoProjectDto.setName(projectDto.getName());
                        }
                    }
                }
                productInfoDto.setProjectList(productInfoProjectDtoList);
            }
        }
        return productInfoDto;
    }

    @Override
    public PageInfo<ProductInfoDto> selectListByIdList(Pager pager, String ids) {
        return produceInfoService.selectListByIdList(pager, ids);
    }

    @Override
    public PageInfo<ProductInfoDto> selectListByDept(Pager pager, ProductInfoDto dto, Long deptId) {
        return produceInfoService.selectListByDept(pager, dto, deptId);
    }

    @Override
    public List<ProductInfoDto> selectListByClassifyId(ProductInfoDto dto, Long classifyId) {
        return produceInfoService.selectListByClassifyId(dto,classifyId);
    }

    @Override
    public Boolean updateVerifyStatusById(Long id, int verifyStatus, Long userId, String userName, String remark, Long applicantId) {
        ProductInfoDto productInfoDto = new ProductInfoDto();
        productInfoDto.setId(id);
        productInfoDto.setVerifyStatus(verifyStatus);
        // 设置操作用户
        productInfoDto.setUpdateUser(applicantId);
        Boolean ok = produceInfoService.update(productInfoDto);
        Ensure.that(ok).isTrue("01000018");
        // 审核成功后自动上架
        if(verifyStatus == BusinessType.VerifyStatusEnum.YESVERIFY.getK()) {
            updateMarketAbleById(id, BusinessType.LicenceTypeEnum.PUT.getK(), userId, userName,"审核成功后自动上架",applicantId);
        }
        return ok;
    }

    @Override
    public Boolean updateMarketAbleById(Long id, Boolean marketAble, Long userId, String userName, String remark, Long applicantId) {
        ProductInfoDto dto = new ProductInfoDto();
        dto.setId(id);
        if(marketAble){
            dto.setShelves(BusinessType.ShelfEnum.PUT.getK());
        }else {
            dto.setStatus(BusinessType.ShelfEnum.PULL.getK());
        }
        // 设置操作用户
        dto.setUpdateUser(applicantId);
        Boolean ok = produceInfoService.update(dto);
        // 如过启用禁用操作失败
        Ensure.that(ok).isTrue("01000019");
        return ok;
    }

    @Override
    public PageInfo<ProductInfoDto> selectListByClassifyIdList(Pager pager,ProductInfoDto dto, String ids) {
        return produceInfoService.selectListByClassifyIdList(pager,dto,ids);
    }
}
